<template>
  <div class="site-add-page">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/ASite_Management' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>站点管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Menu /></el-icon>
          <span>{{ isEditMode ? '编辑站点' : '新增站点' }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面标题 -->
    <div class="page-title">
      <h2>{{ isEditMode ? '编辑站点' : '新增站点' }}</h2>
      <p class="page-desc">填写站点基础信息、选择设备、工具和岗位，保存后即可在列表中查看。</p>
    </div>

    <!-- 表单区域 -->
    <el-card class="form-card" shadow="never">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="120px">
        <!-- 基础信息 -->
        <div class="form-section">
          <div class="section-title">基础信息</div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="站点编号" prop="sitecode">
                <div class="flex-row gap-8">
                  <el-input v-model="form.sitecode" placeholder="请输入站点编号" :disabled="form.autoCode" />
                  <el-switch v-model="form.autoCode" @change="onAutoCodeToggle" />
                  <span class="switch-label">系统编号</span>
                </div>
              </el-form-item>
              <el-form-item label="站点类型" prop="sitetype">
                <el-select v-model="form.sitetype" placeholder="请选择站点类型" class="w-100">
                  <el-option label="类型一" :value="1" />
                  <el-option label="类型二" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="生产线" prop="production_lineid">
                <el-select v-model="form.production_lineid" placeholder="请选择生产线" clearable filterable class="w-100">
                  <el-option v-for="item in productionLineOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="站点位置" prop="site_location">
                <el-input v-model="form.site_location" placeholder="请输入站点位置" />
              </el-form-item>
              <el-form-item label="站点描述" prop="site_Description">
                <el-input v-model="form.site_Description" type="textarea" :rows="3" placeholder="请输入站点描述" />
              </el-form-item>
              <el-form-item label="备注" prop="bz">
                <el-input v-model="form.bz" type="textarea" :rows="3" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="站点名称" prop="sitename">
                <el-input v-model="form.sitename" placeholder="请输入站点名称" />
              </el-form-item>
              <el-form-item label="所在车间" prop="workshopid">
                <el-select v-model="form.workshopid" placeholder="请选择车间" clearable filterable class="w-100">
                  <el-option v-for="item in workshopOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属工序" prop="_processid">
                <el-select v-model="form._processid" placeholder="请选择工序" clearable filterable class="w-100">
                  <el-option v-for="item in processOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio-button :label="1">启用</el-radio-button>
                  <el-radio-button :label="2">禁用</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 站点设备 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-title">站点设备</div>
            <div class="section-actions">
              <el-button type="primary" @click="openDeviceDialog">添加</el-button>
              <el-button @click="handleRemoveDevices" :disabled="!selectedDevices.length">移除</el-button>
            </div>
          </div>
          <el-table :data="form.devices" border stripe class="relation-table" max-height="300">
            <el-table-column type="selection" width="48" @selection-change="handleDeviceSelectionChange" />
            <el-table-column type="index" label="序号" width="64" align="center" />
            <el-table-column prop="devicecode" label="设备编号" min-width="140" />
            <el-table-column prop="devicename" label="设备名称" min-width="140" />
            <el-table-column prop="devicemodel" label="规格型号" min-width="120" />
            <el-table-column prop="device_typetree" label="设备类型" min-width="140" />
            <el-table-column label="设备状态" min-width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status ? 'success' : 'info'">{{ scope.row.status ? '正常' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-link type="danger" @click="handleRemoveDevice(scope.$index)">移除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="section-footer">
            <span class="total-text">设备总数: {{ form.devices.length }}</span>
          </div>
        </div>

        <!-- 站点工具 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-title">站点工具</div>
            <div class="section-actions">
              <el-button type="primary" @click="openToolDialog">添加</el-button>
              <el-button @click="handleRemoveTools" :disabled="!selectedTools.length">移除</el-button>
            </div>
          </div>
          <el-table :data="form.tools" border stripe class="relation-table" max-height="300">
            <el-table-column type="selection" width="48" @selection-change="handleToolSelectionChange" />
            <el-table-column type="index" label="序号" width="64" align="center" />
            <el-table-column prop="work_fixturecode" label="工装夹具编号" min-width="160" />
            <el-table-column prop="work_fixturename" label="工装夹具名称" min-width="160" />
            <el-table-column prop="work_fixturemodels" label="工装夹具型号" min-width="160" />
            <el-table-column prop="work_fixturetypename" label="工装夹具类型" min-width="140" />
            <el-table-column label="数量" min-width="100">
              <template #default="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" :max="9999" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-link type="danger" @click="handleRemoveTool(scope.$index)">移除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="section-footer">
            <span class="total-text">工具总数: {{ totalToolQuantity }}</span>
          </div>
        </div>

        <!-- 站点人员 -->
        <div class="form-section">
          <div class="section-header">
            <div class="section-title">站点人员</div>
            <div class="section-actions">
              <el-button type="primary" @click="openPositionDialog">添加</el-button>
              <el-button @click="handleRemovePositions" :disabled="!selectedPositions.length">移除</el-button>
            </div>
          </div>
          <el-table :data="form.positions" border stripe class="relation-table" max-height="300">
            <el-table-column type="selection" width="48" @selection-change="handlePositionSelectionChange" />
            <el-table-column type="index" label="序号" width="64" align="center" />
            <el-table-column prop="jobnumber" label="岗位编号" min-width="160" />
            <el-table-column prop="jobname" label="岗位名称" min-width="160" />
            <el-table-column label="人数" min-width="100">
              <template #default="scope">
                <el-input-number v-model="scope.row.personcount" :min="1" :max="9999" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-link type="danger" @click="handleRemovePosition(scope.$index)">移除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="section-footer">
            <span class="total-text">人员总数: {{ totalPersonCount }}</span>
          </div>
        </div>
      </el-form>
    </el-card>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <el-button @click="handleCancel">关闭</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
    </div>

    <!-- 选择设备对话框 -->
    <el-dialog v-model="deviceDialog.visible" title="选择设备" width="900px" @closed="onDeviceDialogClosed">
      <el-form :inline="true" :model="deviceDialog.searchForm" class="dialog-search-form">
        <el-form-item>
          <el-input v-model="deviceDialog.searchForm.keyword" placeholder="请输入设备名称/编号" clearable @keyup.enter="handleDeviceSearch" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="deviceDialog.searchForm.device_typetreeid" placeholder="请选择设备类型" clearable class="w-200">
            <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleDeviceReset">重置</el-button>
          <el-button type="primary" @click="handleDeviceSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="deviceDialog.tableData" border stripe :loading="deviceDialog.loading" @selection-change="handleDeviceTableSelectionChange" max-height="400">
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="64" align="center" />
        <el-table-column prop="devicecode" label="设备编号" min-width="140" />
        <el-table-column prop="devicename" label="设备名称" min-width="140" />
        <el-table-column prop="devicemodel" label="规格型号" min-width="120" />
        <el-table-column prop="device_typetree" label="设备类型" min-width="140" />
        <el-table-column label="设置状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'info'">{{ scope.row.status ? '正常' : '停用' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="deviceDialog.pager.page"
          v-model:page-size="deviceDialog.pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="deviceDialog.pager.total"
          @size-change="handleDevicePageSizeChange"
          @current-change="handleDevicePageChange"
        />
      </div>
      <template #footer>
        <el-button @click="deviceDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleDeviceConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 选择工具对话框 -->
    <el-dialog v-model="toolDialog.visible" title="选择工具" width="900px" @closed="onToolDialogClosed">
      <el-form :inline="true" :model="toolDialog.searchForm" class="dialog-search-form">
        <el-form-item>
          <el-input v-model="toolDialog.searchForm.keyword" placeholder="请输入工装夹具名称/编号" clearable @keyup.enter="handleToolSearch" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="toolDialog.searchForm.work_fixturetypeid" placeholder="请选择工装夹具类型" clearable class="w-200">
            <el-option v-for="item in toolTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleToolReset">重置</el-button>
          <el-button type="primary" @click="handleToolSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="toolDialog.tableData" border stripe :loading="toolDialog.loading" @selection-change="handleToolTableSelectionChange" max-height="400">
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="64" align="center" />
        <el-table-column prop="work_fixturecode" label="工装夹具编号" min-width="160" />
        <el-table-column prop="work_fixturename" label="工装夹具名称" min-width="160" />
        <el-table-column prop="work_fixturemodels" label="工装夹具型号" min-width="160" />
        <el-table-column prop="work_fixturetypename" label="工装夹具类型" min-width="140" />
        <el-table-column label="数量" min-width="120">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" :min="1" :max="9999" size="small" placeholder="请输入" />
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="toolDialog.pager.page"
          v-model:page-size="toolDialog.pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="toolDialog.pager.total"
          @size-change="handleToolPageSizeChange"
          @current-change="handleToolPageChange"
        />
      </div>
      <template #footer>
        <el-button @click="toolDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleToolConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 选择岗位对话框 -->
    <el-dialog v-model="positionDialog.visible" title="选择岗位" width="700px" @closed="onPositionDialogClosed">
      <el-form :inline="true" :model="positionDialog.searchForm" class="dialog-search-form">
        <el-form-item>
          <el-input v-model="positionDialog.searchForm.keyword" placeholder="请输入岗位名称/编号" clearable @keyup.enter="handlePositionSearch" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handlePositionReset">重置</el-button>
          <el-button type="primary" @click="handlePositionSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="positionDialog.tableData" border stripe :loading="positionDialog.loading" @selection-change="handlePositionTableSelectionChange" max-height="400">
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="64" align="center" />
        <el-table-column prop="jobnumber" label="岗位编号" min-width="160" />
        <el-table-column prop="jobname" label="岗位名称" min-width="160" />
        <el-table-column label="人数" min-width="120">
          <template #default="scope">
            <el-input-number v-model="scope.row.personcount" :min="1" :max="9999" size="small" placeholder="请输入" />
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="positionDialog.pager.page"
          v-model:page-size="positionDialog.pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="positionDialog.pager.total"
          @size-change="handlePositionPageSizeChange"
          @current-change="handlePositionPageChange"
        />
      </div>
      <template #footer>
        <el-button @click="positionDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handlePositionConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import https from '@/Http/http'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowRight, HomeFilled, Setting, Menu } from '@element-plus/icons-vue'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

// 路由
const route = useRoute()
const router = useRouter()

// 编辑模式
const isEditMode = computed(() => !!route.query.id)
const siteId = computed(() => (route.query.id ? Number(route.query.id) : null))

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: undefined as number | undefined,
  sitecode: '',
  sitename: '',
  sitetype: 1,
  workshopid: undefined as number | undefined,
  _processid: undefined as number | undefined,
  site_location: '',
  status: 1,
  site_Description: '',
  bz: '',
  production_lineid: undefined as number | undefined,
  autoCode: false,
  devices: [] as any[],
  tools: [] as any[],
  positions: [] as any[]
})

// 表单验证规则
const formRules: FormRules = {
  sitecode: [{ required: true, message: '请输入站点编号', trigger: 'blur' }],
  sitename: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  workshopid: [{ required: true, message: '请选择所在车间', trigger: 'change' }],
  _processid: [{ required: true, message: '请选择所属工序', trigger: 'change' }]
}

// 下拉选项
const workshopOptions = ref<{ label: string; value: number }[]>([])
const processOptions = ref<{ label: string; value: number }[]>([])
const productionLineOptions = ref<{ label: string; value: number }[]>([])
const deviceTypeOptions = ref<{ label: string; value: number }[]>([])
const toolTypeOptions = ref<{ label: string; value: number }[]>([])

// 计算属性
const totalToolQuantity = computed(() => form.tools.reduce((sum, item) => sum + (item.quantity || 0), 0))
const totalPersonCount = computed(() => form.positions.reduce((sum, item) => sum + (item.personcount || 0), 0))

// 选中项
const selectedDevices = ref<any[]>([])
const selectedTools = ref<any[]>([])
const selectedPositions = ref<any[]>([])

// 设备对话框
const deviceDialog = reactive({
  visible: false,
  loading: false,
  searchForm: {
    keyword: '',
    device_typetreeid: undefined as number | undefined
  },
  tableData: [] as any[],
  selectedRows: [] as any[],
  pager: { page: 1, size: 10, total: 0 }
})

// 工具对话框
const toolDialog = reactive({
  visible: false,
  loading: false,
  searchForm: {
    keyword: '',
    work_fixturetypeid: undefined as number | undefined
  },
  tableData: [] as any[],
  selectedRows: [] as any[],
  pager: { page: 1, size: 10, total: 0 }
})

// 岗位对话框
const positionDialog = reactive({
  visible: false,
  loading: false,
  searchForm: {
    keyword: ''
  },
  tableData: [] as any[],
  selectedRows: [] as any[],
  pager: { page: 1, size: 10, total: 0 }
})

// 自动生成编号
const genCode = () => {
  const now = new Date()
  const p = (n: number) => `${n}`.padStart(2, '0')
  return `ZDBH${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`
}

const onAutoCodeToggle = () => {
  if (form.autoCode) {
    form.sitecode = genCode()
  }
}

// 获取基础数据
const fetchWorkshops = async () => {
  try {
    const { data } = await https.Reads.get('/ADeviceManagement/AAWorkshopShow')
    const list = Array.isArray(data?.data) ? data.data : []
    workshopOptions.value = list.map((w: any) => ({ label: w.workshopname, value: w.id }))
  } catch (e) {
    workshopOptions.value = []
  }
}

const fetchProcesses = async () => {
  try {
    const { data } = await https.Reads.get('/AManufacturing_process/GetProcessList')
    const list = Array.isArray(data?.data) ? data.data : []
    processOptions.value = list.map((p: any) => ({ label: p.processname, value: p.id }))
  } catch (e) {
    processOptions.value = []
  }
}

const fetchProductionLines = async () => {
  try {
    const { data } = await https.Reads.get('/AProduction_Line_Management/GetProductionLineManagementList', {
      params: { PageIndex: 1, PageSize: 1000 }
    })
    const list = Array.isArray(data?.data) ? data.data : []
    productionLineOptions.value = list.map((pl: any) => ({ label: pl.production_linename, value: pl.id }))
  } catch (e) {
    productionLineOptions.value = []
  }
}

const fetchDeviceTypes = async () => {
  try {
    const { data } = await https.Reads.get('/ADeviceManagement/Showdevice_typetreeModel')
    const buildOptions = (list: any[]): any[] => {
      const result: any[] = []
      const traverse = (items: any[]) => {
        items.forEach((item: any) => {
          if (item.value) {
            result.push({ label: item.label, value: item.value })
          }
          if (item.children && item.children.length) {
            traverse(item.children)
          }
        })
      }
      traverse(Array.isArray(list) ? list : [])
      return result
    }
    deviceTypeOptions.value = buildOptions(data?.data ?? [])
  } catch (e) {
    deviceTypeOptions.value = []
  }
}

const fetchToolTypes = async () => {
  try {
    const { data } = await https.Reads.get('/Applicae/work_fixturetypelist', { params: { Pageindex: 1, PageSize: 1000 } })
    const list = Array.isArray(data?.data) ? data.data : []
    toolTypeOptions.value = list.map((t: any) => ({ label: t.work_fixturetypename, value: t.id }))
  } catch (e) {
    toolTypeOptions.value = []
  }
}

// 设备相关方法
const openDeviceDialog = () => {
  deviceDialog.visible = true
  fetchDeviceList()
}

const fetchDeviceList = async () => {
  deviceDialog.loading = true
  try {
    const { data } = await https.Reads.get('/ADeviceManagement/AEquipment_LedgerShow', {
      params: {
        devicenameorcode: deviceDialog.searchForm.keyword || undefined,
        device_typetreeid: deviceDialog.searchForm.device_typetreeid || 0,
        workshopid: 0,
        PageIndex: deviceDialog.pager.page,
        PageSize: deviceDialog.pager.size
      }
    })
    const list = Array.isArray(data?.data) ? data.data : []
    deviceDialog.tableData = list
    deviceDialog.pager.total = data?.totalCount ?? data?.TotalCount ?? list.length
  } catch (e) {
    deviceDialog.tableData = []
    deviceDialog.pager.total = 0
  } finally {
    deviceDialog.loading = false
  }
}

const handleDeviceSearch = () => {
  deviceDialog.pager.page = 1
  fetchDeviceList()
}

const handleDeviceReset = () => {
  deviceDialog.searchForm.keyword = ''
  deviceDialog.searchForm.device_typetreeid = undefined
  handleDeviceSearch()
}

const handleDeviceTableSelectionChange = (rows: any[]) => {
  deviceDialog.selectedRows = rows
}

const handleDeviceConfirm = () => {
  const newDevices = deviceDialog.selectedRows.filter(
    (row) => !form.devices.some((d) => d.deviceid === row.id)
  )
  form.devices.push(
    ...newDevices.map((row) => ({
      deviceid: row.id,
      devicecode: row.devicecode,
      devicename: row.devicename,
      devicemodel: row.devicemodel,
      device_typetree: row.device_typetree,
      status: row.status
    }))
  )
  deviceDialog.visible = false
  ElMessage.success('添加设备成功')
}

const handleDeviceSelectionChange = (rows: any[]) => {
  selectedDevices.value = rows
}

const handleRemoveDevice = (index: number) => {
  form.devices.splice(index, 1)
}

const handleRemoveDevices = () => {
  const ids = selectedDevices.value.map((d) => d.deviceid)
  form.devices = form.devices.filter((d) => !ids.includes(d.deviceid))
  selectedDevices.value = []
}

const handleDevicePageSizeChange = () => {
  fetchDeviceList()
}

const handleDevicePageChange = () => {
  fetchDeviceList()
}

const onDeviceDialogClosed = () => {
  deviceDialog.selectedRows = []
}

// 工具相关方法
const openToolDialog = () => {
  toolDialog.visible = true
  fetchToolList()
}

const fetchToolList = async () => {
  toolDialog.loading = true
  try {
    const { data } = await https.Reads.get('/Applicae/work_fixturelist', {
      params: {
        Pageindex: toolDialog.pager.page,
        PageSize: toolDialog.pager.size,
        work_fixturename: toolDialog.searchForm.keyword || undefined,
        work_fixturetypeid: toolDialog.searchForm.work_fixturetypeid || undefined
      }
    })
    const list = Array.isArray(data?.data) ? data.data : []
    toolDialog.tableData = list.map((item: any) => ({
      ...item,
      quantity: 1
    }))
    toolDialog.pager.total = data?.totalCount ?? data?.TotalCount ?? list.length
  } catch (e) {
    toolDialog.tableData = []
    toolDialog.pager.total = 0
  } finally {
    toolDialog.loading = false
  }
}

const handleToolSearch = () => {
  toolDialog.pager.page = 1
  fetchToolList()
}

const handleToolReset = () => {
  toolDialog.searchForm.keyword = ''
  toolDialog.searchForm.work_fixturetypeid = undefined
  handleToolSearch()
}

const handleToolTableSelectionChange = (rows: any[]) => {
  toolDialog.selectedRows = rows
}

const handleToolConfirm = () => {
  const newTools = toolDialog.selectedRows.filter((row) => !form.tools.some((t) => t.toolid === row.id))
  form.tools.push(
    ...newTools.map((row) => ({
      toolid: row.id,
      work_fixturecode: row.work_fixturecode,
      work_fixturename: row.work_fixturename,
      work_fixturemodels: row.work_fixturemodels,
      work_fixturetypename: row.work_fixturetypename || '',
      quantity: row.quantity || 1
    }))
  )
  toolDialog.visible = false
  ElMessage.success('添加工具成功')
}

const handleToolSelectionChange = (rows: any[]) => {
  selectedTools.value = rows
}

const handleRemoveTool = (index: number) => {
  form.tools.splice(index, 1)
}

const handleRemoveTools = () => {
  const ids = selectedTools.value.map((t) => t.toolid)
  form.tools = form.tools.filter((t) => !ids.includes(t.toolid))
  selectedTools.value = []
}

const handleToolPageSizeChange = () => {
  fetchToolList()
}

const handleToolPageChange = () => {
  fetchToolList()
}

const onToolDialogClosed = () => {
  toolDialog.selectedRows = []
}

// 岗位相关方法
const openPositionDialog = () => {
  positionDialog.visible = true
  fetchPositionList()
}

const fetchPositionList = async () => {
  positionDialog.loading = true
  try {
    const { data } = await https.Reads.get('/RBAC/ShowJob', {
      params: {
        pageindex: positionDialog.pager.page,
        pagesize: positionDialog.pager.size,
        name: positionDialog.searchForm.keyword || undefined
      }
    })
    const list = Array.isArray(data?.data) ? data.data : Array.isArray(data?.Data) ? data.Data : []
    positionDialog.tableData = list.map((item: any) => ({
      ...item,
      personcount: 1
    }))
    positionDialog.pager.total = data?.totalCount ?? data?.TotalCount ?? list.length
  } catch (e) {
    positionDialog.tableData = []
    positionDialog.pager.total = 0
  } finally {
    positionDialog.loading = false
  }
}

const handlePositionSearch = () => {
  positionDialog.pager.page = 1
  fetchPositionList()
}

const handlePositionReset = () => {
  positionDialog.searchForm.keyword = ''
  handlePositionSearch()
}

const handlePositionTableSelectionChange = (rows: any[]) => {
  positionDialog.selectedRows = rows
}

const handlePositionConfirm = () => {
  const newPositions = positionDialog.selectedRows.filter((row) => !form.positions.some((p) => p.positionid === row.id))
  form.positions.push(
    ...newPositions.map((row) => ({
      positionid: row.id,
      jobnumber: row.jobnumber,
      jobname: row.jobname,
      personcount: row.personcount || 1
    }))
  )
  positionDialog.visible = false
  ElMessage.success('添加岗位成功')
}

const handlePositionSelectionChange = (rows: any[]) => {
  selectedPositions.value = rows
}

const handleRemovePosition = (index: number) => {
  form.positions.splice(index, 1)
}

const handleRemovePositions = () => {
  const ids = selectedPositions.value.map((p) => p.positionid)
  form.positions = form.positions.filter((p) => !ids.includes(p.positionid))
  selectedPositions.value = []
}

const handlePositionPageSizeChange = () => {
  fetchPositionList()
}

const handlePositionPageChange = () => {
  fetchPositionList()
}

const onPositionDialogClosed = () => {
  positionDialog.selectedRows = []
}

// 加载站点详情（编辑模式）
const loadSiteDetail = async () => {
  if (!siteId.value) return
  try {
    const { data } = await https.Reads.get('/ASite/ASite_ManagementDetail', {
      params: { id: siteId.value }
    })
    if (isRequestSuccess(data)) {
      const detail = data.data || data.Data
      form.id = detail.id
      form.sitecode = detail.sitecode
      form.sitename = detail.sitename
      form.sitetype = detail.sitetype
      form.workshopid = detail.workshopid
      form._processid = detail._processid
      form.site_location = detail.site_location || ''
      form.status = detail.status
      form.site_Description = detail.site_Description || ''
      form.bz = detail.bz || ''
      form.devices = (detail.devices || []).map((d: any) => ({
        deviceid: d.deviceid,
        devicecode: d.devicecode,
        devicename: d.devicename,
        devicemodel: d.devicemodel,
        device_typetree: d.device_typetree,
        status: d.status
      }))
      form.tools = (detail.tools || []).map((t: any) => ({
        toolid: t.toolid,
        work_fixturecode: t.work_fixturecode,
        work_fixturename: t.work_fixturename,
        work_fixturemodels: t.work_fixturemodels,
        work_fixturetypename: t.work_fixturetypename,
        quantity: t.quantity
      }))
      form.positions = (detail.positions || []).map((p: any) => ({
        positionid: p.positionid,
        jobnumber: p.jobnumber,
        jobname: p.jobname,
        personcount: p.personcount
      }))
    }
  } catch (e) {
    ElMessage.error('加载站点详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = {
        id: form.id,
        sitecode: form.sitecode,
        sitename: form.sitename,
        sitetype: form.sitetype,
        workshopid: form.workshopid,
        _processid: form._processid,
        site_location: form.site_location,
        status: form.status,
        site_Description: form.site_Description,
        bz: form.bz,
        production_lineid: form.production_lineid,
        deviceIds: form.devices.map((d) => d.deviceid),
        toolItems: form.tools.map((t) => ({ toolid: t.toolid, quantity: t.quantity })),
        positionItems: form.positions.map((p) => ({ positionid: p.positionid, personcount: p.personcount }))
      }
      const url = isEditMode.value ? '/ASiteADU/SiteManagementEdit' : '/ASiteADU/SiteManagementAdd'
      const { data } = await https.Writes.post(url, payload)
      if (isRequestSuccess(data)) {
        ElMessage.success(isEditMode.value ? '编辑站点成功' : '新增站点成功')
        router.push('/ASite_Management')
      } else {
        ElMessage.error(getResponseMessage(data, '操作失败'))
      }
    } catch (e) {
      ElMessage.error(getErrorMessage(e, '操作失败'))
    } finally {
      submitLoading.value = false
    }
  })
}

const handleCancel = () => {
  router.push('/ASite_Management')
}

// 初始化
onMounted(async () => {
  await Promise.all([
    fetchWorkshops(),
    fetchProcesses(),
    fetchProductionLines(),
    fetchDeviceTypes(),
    fetchToolTypes()
  ])
  if (isEditMode.value) {
    await loadSiteDetail()
  } else {
    form.autoCode = true
    form.sitecode = genCode()
  }
})
</script>

<style scoped>
.site-add-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.page-title {
  margin-bottom: 16px;
}

.page-title h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.page-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.form-card {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-actions {
  display: flex;
  gap: 12px;
}

.relation-table {
  width: 100%;
  margin-bottom: 12px;
}

.section-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.total-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 24px 0;
}

.dialog-search-form {
  margin-bottom: 16px;
}

.dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.flex-row {
  display: flex;
  align-items: center;
}

.gap-8 {
  gap: 8px;
}

.w-100 {
  width: 100%;
}

.w-200 {
  width: 200px;
}

.switch-label {
  font-size: 14px;
  color: #606266;
}
</style>

